const fs = require('fs');
const readline = require('readline');
const os = require('os');

const file = 'index.html';

const output = fs.createWriteStream('test.html');

const imgReg = /<img.*?(?:>|\/>)/gi;
const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;

let replaceSources = new Map();

let allLine = 0;

const rl = readline.createInterface({
    input: fs.createReadStream(file),
});

rl.on('line', (line) => {
    const imgArr = line.match(imgReg);
    if (imgArr != null) {
        for (const imgArrItem of imgArr) {
            const src = imgArrItem.match(srcReg);
            if (src[1]) {
                replaceSources.set(src[1], src[1]);
            }
        }
    }
    allLine++;
});

rl.on('close', () => {
    console.log('read file complete');
    console.log([...replaceSources.values()]);
    replaceSrcFn(replaceSources);
});

function replaceSrcFn(map) {
    console.log('start uploading source');
    let computedRes = new Map();

    function api(oldLink) {
        return new Promise(function (resolve, reject) {
            setTimeout(() => {
                resolve({oldLink: oldLink, newLink: oldLink + 'hasReplace'});
                console.log(`${oldLink} replace success`);
            }, 3000)
        })
    }

    function* queue() {
        for (const mapItem of [...map.values()]) {
            yield api(mapItem)
        }
    }

    function runApi(generator) {
        const g = generator();
        const go = function (data) {
            let result = g.next(data);
            if (result.done) {
                console.log('all link has been replaced succeed');
                console.log(computedRes);
                writeFile(computedRes);
                return result.value;
            }
            result.value.then((data) => {
                computedRes.set(data.oldLink, data.newLink);
                go(data);
            })
        };
        go();
    }

    runApi(queue);
}

function writeFile(map) {
    console.log('start write file...');

    const w = readline.createInterface({
        input: fs.createReadStream(file),
    });

    let write = 0;

    w.on('line', (line) => {
        const imgArr = line.match(imgReg);
        let outputSrc;
        if (imgArr != null) {
            for (const imgArrItem of imgArr) {
                const src = imgArrItem.match(srcReg);
                if (src[1]) {
                    outputSrc = line.replace(src[1], map.get(src[1]));
                }
            }
        } else {
            outputSrc = line;
        }
        output.write(outputSrc + os.EOL,()=>{
            write++;
            if(allLine == write){
                console.log('file write complete');
            }
        });
    });
}